﻿Imports System.ServiceProcess 'For the service controller
Imports Microsoft.Msdn.Samples.BITS 'For the bits classes (joblist, job, etc)

Public Class FrmMain
    Dim FrmCurrentDownloads As New FrmDownloads
    Private Controller As New ServiceController 'Controller for checking the state of the BITS service
    Private WithEvents BITS_Events As New JobEvents 'Classes for tracking events of the jobs
    Private WithEvents FrmFrmServiceNotRunning As New FrmServiceNotRunning 'Form that tells the user, that the BITS service is not running

    ''' <summary>
    ''' Clears the lists and fills them with the current jobs and files
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub _BuildLists()
        Dim Jobs As JobCollection
        Dim Job As Job
        Dim i, j, FilesTotal, Running, Suspended, OnError, Finished, CurrentFile As Integer
        Dim lstJob, lstFile As ListViewItem

        Try
            Controller.Refresh() 'Rereads the states of the BITS service
            If Controller.Status <> ServiceControllerStatus.Running Then 'Is BITS not running?
                FrmFrmServiceNotRunning.TimCheckService.Start() 'Start the timer of the "Service not Running" Window
                TimReload.Stop() 'Stops the timer of this form
                FrmFrmServiceNotRunning.ShowDialog() 'Show the "Service Not Running" Window
                Exit Sub 'Exit this sub
            End If 'If Controller.Status <> ServiceControllerStatus.Running Then
        Catch ex As Exception
            StatusMain.Text = "Cannot register to service!"
        End Try
        

        'If the service is not running or the controller and BITS wrapper have not been reset, an exception can occur.
        'This try statement will handle this case and leave the sub
        Try
            Jobs = ModBITS.BITS.GetListofJobs() 'Read all BITS jobs
        Catch ex As Exception 'Catch any exception
            'TODO: Enumerate various exceptions
            StatusMain.Text = "Cannot get list of jobs!"
            Exit Sub 'Leave sub
        End Try

        'Any selection in the job list will be lost, if the list is cleared. Therefore the list is just updated, while there
        'have been no changes to the jobs (add/remove).
        If Jobs.Count <> LViewJobs.Items.Count Then 'Is the number of jobs and the no. of list entries different (Last run there have been more/less jobs)
            LViewJobs.Items.Clear() 'Clear the job list
        End If 'If Jobs.Count <> LViewJobs.Items.Count Then



        FilesTotal = 0 'Reset the file counter
        For j = 0 To Jobs.Count - 1 'Enumerate the jobs
            FilesTotal = FilesTotal + Jobs(j).Files.Count 'Adds the file in the current job to the sum of files
        Next 'For j = 0 To Jobs.Count - 1

        'Any selection in the file list will be lost, if the list is cleared. Therefore the list is just updated, while there
        'have been no changes to the number of files.
        If FilesTotal <> LViewDownloads.Items.Count Then 'Has the number of files changed?
            LViewDownloads.Items.Clear() 'Clear the list of files
        End If 'If FilesTotal <> LViewDownloads.Items.Count Then

        'Reset the state counter for the jobs
        Suspended = 0
        Running = 0
        OnError = 0
        Finished = 0

        'Reset the current file enumerator (-1, because the first items has to be zero!)
        CurrentFile = -1

        Try
            'This two loops are enumerating all jobs (j-loop) and within all files per job (i-loop)
            For j = 0 To Jobs.Count - 1 'Enumerating all jobs
                Job = Jobs.Item(j) 'Retrieve the job form the list of jobs
                For i = 0 To Job.Files.Count - 1 'Enumerating all files in the job
                    CurrentFile += 1
                    If LViewDownloads.Items.Count <> FilesTotal Then 'No. of jobs different to no. of list entries?
                        'In this block the no. of jobs have changed, therefore the list have been cleared and entry have to be added


                        'Add file to the listview
                        lstFile = New ListViewItem 'Create new instance of list entry
                        Dim Prg As New ProgressBar

                        lstFile.Text = Job.Files(i).LocalName 'Add local file name to the list entry
                        lstFile.SubItems.Add(Job.Files(i).RemoteName) 'Add remote file name to the list entry
                        If Job.Files(i).Progress.BytesTotal < 1000000000000000000 Then 'BITS sets a very high file size, if correct file size have not been ascertained. Is the value lower, Bandyt BITS assumes, that the file size is correct
                            'In this block the file size is assumed known
                            lstFile.SubItems.Add(Strings.Format(Job.Files(i).Progress.BytesTotal, "##,##0")) 'Add total file size to list entry (With digit grouping)
                            lstFile.SubItems.Add(Strings.Format(Job.Files(i).Progress.BytesTransferred, "##,##0")) 'Add transferred bytes to list entry (With digit grouping)
                            lstFile.SubItems.Add(Strings.Format((Job.Files(i).Progress.BytesTransferred / Job.Files(i).Progress.BytesTotal), "##0.00%")) 'Add progress to the list entry (As percentage)


                            'Prg.Minimum = 0
                            'Prg.Maximum = Job.Files(i).Progress.BytesTotal
                            'Prg.Value = Job.Files(i).Progress.BytesTransferred
                            'Prg.Style = ProgressBarStyle.Continuous
                        Else 'If Job.Files(i).Progress.BytesTotal < 1000000000000000000 Then
                            'In this block the file size is assumed unknown
                            lstFile.SubItems.Add("?") 'Add a ? to the list entry, indicating, that file size is unknown
                            lstFile.SubItems.Add("0") 'Add 0 Bytes as progress to the list entry
                            lstFile.SubItems.Add("0,00%") 'Add 0% as progress to the list entry
                            'Prg.Minimum = 0
                            'Prg.Maximum = 100
                            'Prg.Value = 0
                            'Prg.Style = ProgressBarStyle.Continuous
                        End If 'If Job.Files(i).Progress.BytesTotal < 1000000000000000000 Then
                        lstFile.Tag = j & "\" & i 'Add job no. and file no. as tag to the list entry
                        LViewDownloads.Items.Add(lstFile) 'Add new entry to the file list
                        'Prg.Bounds = LViewDownloads.Items(LViewDownloads.Items.Count - 1).SubItems(4).Bounds
                        'LViewDownloads.Controls.Add(Prg)

                    Else 'If LViewDownloads.Items.Count <> Jobs.Count Then
                        'In this block the no. of job have not been changed, therefore the list entries have to be updated only


                        LViewDownloads.Items(CurrentFile).Text = Job.Files(i).LocalName 'Update local file name
                        LViewDownloads.Items(CurrentFile).SubItems(1).Text = Job.Files(i).RemoteName 'Update remote file name
                        If Job.Files(i).Progress.BytesTotal < 1000000000000000000 Then 'Check if file size is below threshold, to ascertain if file size is known
                            'In this block, the file size is assumed known
                            LViewDownloads.Items(CurrentFile).SubItems(2).Text = (Strings.Format(Job.Files(i).Progress.BytesTotal, "##,##0")) 'Update file size
                            LViewDownloads.Items(CurrentFile).SubItems(3).Text = (Strings.Format(Job.Files(i).Progress.BytesTransferred, "##,##0")) 'Update progress in bytes
                            LViewDownloads.Items(CurrentFile).SubItems(4).Text = (Strings.Format((Job.Files(i).Progress.BytesTransferred / Job.Files(i).Progress.BytesTotal), "##0.00%")) 'update file size in percent
                            'Dim Prg As ProgressBar
                            'Prg = LViewDownloads.Controls(CurrentFile)
                            'Prg.Minimum = 0
                            'Prg.Maximum = Job.Files(i).Progress.BytesTotal
                            'Prg.Value = Job.Files(i).Progress.BytesTransferred

                        Else
                            'In this block the file size is assumed unknown
                            LViewDownloads.Items(CurrentFile).SubItems(2).Text = ("?") 'Upadates ? as file size, indicating that file size is unknown
                            LViewDownloads.Items(CurrentFile).SubItems(3).Text = ("0") 'Updates 0 Bytes as progress
                            LViewDownloads.Items(CurrentFile).SubItems(4).Text = ("0,00%") 'Updates 0% as progress
                            'Dim Prg As ProgressBar
                            'Prg = LViewDownloads.Controls(CurrentFile)
                            'Prg.Minimum = 0
                            'Prg.Maximum = 100
                            'Prg.Value = 0
                        End If

                        LViewDownloads.Items(CurrentFile).Tag = j & "\" & i 'Update job no. and file no.
                    End If
                    'End of file enumeration
                Next


                'If the no. of jobs is different to the no. of job list entries, the job lists have been cleared and entries
                'have to be added instead of updated.
                If LViewJobs.Items.Count <> Jobs.Count Then 'Is the no. of jobs different to the no. of job list entries?
                    'In this block the no. of jobs is different, therefore the entries have to be added

                    lstJob = New ListViewItem 'Create new list entry
                    lstJob.Text = Job.DisplayName 'Add job name
                    lstJob.SubItems.Add(Job.Files.Count) 'Add no. of files
                    lstJob.SubItems.Add(Job.State.ToString) 'Add state
                    lstJob.SubItems.Add(Job.GetOwnerName) 'Add owner
                    lstJob.SubItems.Add(Job.Description) 'Add description
                    LViewJobs.Items.Add(lstJob) 'Add entry to list
                Else 'If LViewJobs.Items.Count <> Jobs.Count Then
                    'In this block the no. of jobs is equal the no. of job list entries, therefore the entries are updated, not added
                    LViewJobs.Items(j).Text = Job.DisplayName 'Update job name
                    LViewJobs.Items(j).SubItems(1).Text = Job.Files.Count 'Update file count
                    LViewJobs.Items(j).SubItems(2).Text = Job.State.ToString 'Update state
                    LViewJobs.Items(j).SubItems(3).Text = Job.GetOwnerName 'Update owner
                    LViewJobs.Items(j).SubItems(4).Text = Job.Description 'Update description
                End If 'If LViewJobs.Items.Count <> Jobs.Count Then

                'This select statement determines the state of the job and updates the state counter 
                Select Case Job.State
                    Case Is = JobState.Acknowledged 'Acknowledged is counter as running
                        Running = Running + 1
                    Case Is = JobState.Cancelled
                        'Cancelled is not counted. For further development
                    Case Is = JobState.Connecting 'Connceting is counted as running
                        Running = Running + 1
                    Case Is = JobState.Errors 'This state adds to "error"
                        OnError = OnError + 1
                    Case Is = JobState.Queued 'Queued if counted as running
                        Running = Running + 1
                    Case Is = JobState.Suspended 'This state adds to "suspended"
                        Suspended = Suspended + 1
                    Case Is = JobState.Transferred 'This state adds to "transferred"
                        Finished = Finished + 1
                    Case Is = JobState.Transferring 'Transferring is counted as running
                        Running = Running + 1
                    Case Is = JobState.TransientError 'TransientError is counted as error
                        OnError = OnError + 1
                End Select 'Select Case Job.State

                If Jobs.Item(j).State = JobState.Errors Or Jobs.Item(j).State = JobState.TransientError Then
                    Jobs.Item(j).ResumeJob()
                End If

                'end of job enumeration
            Next 'For j = 0 To Jobs.Count - 1
        Catch ex As Exception
            StatusMain.Text = "Error enumerating jobs!"
        End Try

        Try
            'Updates the text of the tray icon
            NotifyIcon.Text = "Bandyt BITS" & vbCrLf & Suspended & " suspended" & vbCrLf & Running & " running" & vbCrLf & Finished & " finished" & vbCrLf & OnError & " with errors"
        Catch ex As Exception
            StatusMain.Text = "Error updating tray icon"
        End Try
        
    End Sub

    Private Sub FrmMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        NotifyIcon.Visible = False
    End Sub 'Private Sub _BuildLists()


    Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Controller.ServiceName = "BITS" 'Sets the service name to BITS (Internal name of the Background Intelligent Transfer Service)
        StatusService.Text = "Status of Service: " & Controller.Status.ToString 'Shows the service state in the status bar

        'Try to upgrade the settings. This is required if the version of the sofware has changed. If not
        'upgraded, the settings will fall back to default.
        Try
            My.Settings.Upgrade()
        Catch ex As Exception

        End Try
        My.Settings.Reload()
        'This loop adds all current jobs to the event manager
        For Each Job In ModBITS.BITS.GetListofJobs 'Enumerates all jobs
            BITS_Events.AddJob(Job) 'Add job to the event handler
        Next 'For Each Job In ModBITS.BITS.GetListofJobs

        NotifyIcon.Icon = Me.Icon 'Sets this forms icon as notify icon
        NotifyIcon.Text = "Bandyt BITS" 'Sets the text of the tray icon
        NotifyIcon.Visible = True 'Shows the tray icon
        Call TabJobs_SelectedIndexChanged(Me, e) 'Call the Tab control to display the correct tab
        'Reads the setting for the update speed
        If My.Settings.Refresh = 0 Then 'No update wished?
            TimReload.Stop() 'Stop the timer
        Else 'If My.Settings.Refresh = 0 Then
            Select Case My.Settings.Refresh
                Case Is = 300
                    MnuViewUpdatespeedVeryHigh.Checked = True
                Case Is = 800
                    MnuViewUpdatespeedHigh.Checked = True
                Case Is = 1500
                    MnuViewUpdatespeedNormal.Checked = True
                Case Is = 3000
                    MnuViewUpdatespeedSlow.Checked = True
                Case Else
            End Select
            TimReload.Interval = My.Settings.Refresh 'Sets the interval to the selected value
            TimReload.Start() 'Starts the timer
        End If 'If My.Settings.Refresh = 0 Then
        _BuildLists() 'Fill the lists
    End Sub 'Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    ''' <summary>
    ''' This sub is called if the FrmServiceNotRunning triggers the event indicating, that BITS not running and is now back online
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub _ServiceBackRunning() Handles FrmFrmServiceNotRunning.EVENT_SERVICERUNNING
        Controller = Nothing 'Reset the Service Controller
        Controller = New ServiceController 'Create a new instance of the Controller
        Controller.ServiceName = "BITS" 'Tell Controller to check the BITS service
        Controller.Refresh() 'Reload the information of the service
        ModBITS._Reload() 'Call the _reload sub to reset and reload the BITS wrapper
        TimReload.Start() 'Start the timmer
    End Sub 'Private Sub _ServiceBackRunning() Handles FrmFrmServiceNotRunning.EVENT_SERVICERUNNING

    ''' <summary>
    ''' This sub handles the event, that one or more jobs are having errors
    ''' </summary>
    ''' <param name="sender">The object which raised the event</param>
    ''' <param name="e">Additional job information</param>
    ''' <remarks></remarks>
    Private Sub _JobError(ByVal sender As Object, ByVal e As JobErrorEventArgs) Handles BITS_Events.JobError
        If My.Settings.Warn_Errors Then 'Does the user wish to be notified?
            NotifyIcon.BalloonTipIcon = ToolTipIcon.Error 'Show message as error
            'Diaplay the message with some additional information about the error
            NotifyIcon.BalloonTipText = "An error occured in your job '" & e.Job.DisplayName & "'!" & vbCrLf & "The description is " & vbCrLf & e.GetErrorDescription.ToString
            NotifyIcon.BalloonTipTitle = "Job Error" 'Set the title of the message
            NotifyIcon.ShowBalloonTip(10000) 'Show the message for 10 seconds
        End If 'If My.Settings.Warn_Errors Then
    End Sub 'Private Sub _JobError(ByVal sender As Object, ByVal e As JobErrorEventArgs) Handles BITS_Events.JobError

    ''' <summary>
    ''' Handler for the Job Finished Event
    ''' </summary>
    ''' <param name="sender">The object which raised the event</param>
    ''' <param name="e">Additional job information</param>
    ''' <remarks></remarks>
    Private Sub _JobFinished(ByVal sender As Object, ByVal e As JobEventArgs) Handles BITS_Events.JobTransferred
        Dim i As Integer 'Enumerator for files in the job
        Dim Text As String 'Notification text

        Text = "" 'Reset the text
        NotifyIcon.BalloonTipIcon = ToolTipIcon.Info 'Show message as information
        If My.Settings.Auto_SaveToFile = False Then 'Should the job be finished automatically?
            'Do not complete the job

            'Message, that job is done, but files are not available
            Text = "Your Job" & vbCrLf & vbCrLf & "'" & e.JobName & "'" & vbCrLf & vbCrLf & "has finished downloading. You have to select the 'Finished and save to file' menu entry in the Job Menu in order to be able to access the files downloaded."
        Else 'If My.Settings.Auto_SaveToFile = False Then
            'Do complete the job automatically

            'Message that job is done and files are available
            Text = "Your Job" & vbCrLf & vbCrLf & "'" & e.JobName & "'" & vbCrLf & vbCrLf & "has finished downloading and it has been completed automatically. You can now access the file(s) from the following location(s):"
            'Enumerates the files in the job and adds their local name to the message
            For i = 0 To e.Job.Files.Count - 1 'Enumerate files
                Text = Text & vbCrLf & e.Job.Files(i).LocalName 'Add local file name to message
            Next 'For i = 0 To e.Job.Files.Count - 1
            e.Job.Complete() 'Complete the job
        End If 'If My.Settings.Auto_SaveToFile = False Then
        NotifyIcon.BalloonTipText = Text 'Assign text to the balloon top
        NotifyIcon.BalloonTipTitle = "Job Download Completed" 'Set title for the message
        NotifyIcon.ShowBalloonTip(10000) 'Show message for 10 seconds
    End Sub 'Private Sub _JobFinished(ByVal sender As Object, ByVal e As JobEventArgs) Handles BITS_Events.JobTransferred

    ''' <summary>
    ''' The sub is called if the user clicks on the "add job" icon in the toolbar
    ''' </summary>
    ''' <param name="sender">Object which called the sub</param>
    ''' <param name="e">Parameter for this event</param>
    ''' <remarks></remarks>
    Private Sub ToolStripAddDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripAddDownload.Click
        Dim Frm As New FrmAddJob 'Crates a new instance of FrmAddJob
        AddHandler Frm.JobAdded, AddressOf _JobAdded 'Add the handler to the Newly Created Job event
        Frm.Show() 'Show the Add Job form
    End Sub 'Private Sub ToolStripAddDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripAddDownload.Click

    ''' <summary>
    ''' Handler for the Job Added Event
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub _JobAdded()
        Dim Job As Job 'Container for the job information
        Dim Jobs As JobCollection 'Represents all BITS jobs

        StatusSystemMessage.Text = "Job has been added!" 'Display the message that a job has been added
        Jobs = ModBITS.BITS.GetListofJobs 'Get list of jobs
        Job = Jobs(Jobs.Count - 1) 'Get information about the latest job
        BITS_Events.AddJob(Job) 'Add the job to the event handler
        _BuildLists() 'Rebuild lists
    End Sub 'Private Sub _JobAdded()


    Private Sub MnuJobsDeleteAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsDeleteAll.Click
        Dim answer As MsgBoxResult
        Dim Jobs As JobCollection

        answer = MsgBox("Are you sure that you want to delete all jobs on this maschine?", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, "Delete All Jobs?")
        If answer = MsgBoxResult.Yes Then
            Try
                Jobs = ModBITS.BITS.GetListofJobs(JobType.AllUsers)

                For i = 0 To Jobs.Count - 1
                    Jobs(i).Cancel()
                Next
                StatusSystemMessage.Text = "All jobs deleted"
            Catch ex As Exception
                StatusSystemMessage.Text = "Error deleting all jobs"
            End Try

        End If
    End Sub


    ''' <summary>
    ''' Sets the enabled property for the "file" and "job" menu entries
    ''' </summary>
    ''' <param name="Jobs">Are the job menu entries enabled?</param>
    ''' <param name="Files">Are the file menu entries enabled?</param>
    ''' <remarks></remarks>
    Private Sub _EnableMenus(ByVal Jobs As Boolean, ByVal Files As Boolean)
        MnuFileProperties.Enabled = Files

        MnuJobsDelete.Enabled = Jobs
        MnuJobsProperties.Enabled = Jobs
        MnuJobsResume.Enabled = Jobs
        MnuJobsSuspend.Enabled = Jobs
        MnuJobsFinish.Enabled = Jobs
    End Sub
    Private Sub TabJobs_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabJobs.SelectedIndexChanged
        Select Case TabJobs.SelectedIndex
            Case Is = 0
                _EnableMenus(False, True)
            Case Is = 1
                _EnableMenus(True, False)
        End Select
    End Sub

    Private Sub MnuJobsDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsDelete.Click
        If LViewJobs.SelectedIndices.Count < 1 Then
            MsgBox("No job selected!", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Delete Job")
            Exit Sub
        End If

        If MsgBox("Are you sure that you want to delete the selected job?", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, "Delete Job?") = MsgBoxResult.Yes Then
            Dim Jobs As JobCollection
            Dim Job As Job

            Jobs = ModBITS.BITS.GetListofJobs
            Job = Jobs(LViewJobs.SelectedIndices.Item(0))
            Job.Cancel()
            Me._BuildLists()
        End If
    End Sub

    Private Sub CMnuLViewJobsDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuLViewJobsDelete.Click
        Call MnuJobsDelete_Click(sender, e)
    End Sub

    Private Sub MnuJobsNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsNew.Click
        ToolStripAddDownload_Click(sender, e)
    End Sub

    Private Sub TimReload_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimReload.Tick
        _BuildLists()
    End Sub

    Private Sub MnuJobsResumeAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsResumeAll.Click
        Dim Jobs As JobCollection
        Dim Job As Job

        Jobs = ModBITS.BITS.GetListofJobs
        For Each Job In Jobs
            Job.ResumeJob()
        Next
        StatusSystemMessage.Text = "All jobs resumed"
    End Sub

    Private Sub MnuJobsSuspendAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsSuspendAll.Click
        Dim Jobs As JobCollection
        Dim Job As Job

        Jobs = ModBITS.BITS.GetListofJobs
        For Each Job In Jobs
            Job.Suspend()
        Next
        StatusSystemMessage.Text = "All jobs suspended"
    End Sub

    Private Sub MnuFileExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFileExit.Click
        NotifyIcon.Visible = False
        End
    End Sub




    Private Sub MnuJobsResume_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsResume.Click
        If LViewJobs.SelectedItems.Count < 1 Then
            MsgBox("You have to select a job to resume!", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "No item selected")
            Exit Sub
        End If
        If ModBITS._ResumeJob(LViewJobs.SelectedIndices.Item(0)) <> True Then
            StatusSystemMessage.Text = "Error resuming job"
        Else
            StatusSystemMessage.Text = "Resuming job"
        End If
    End Sub

    Private Sub MnuJobsSuspend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsSuspend.Click
        If LViewJobs.SelectedItems.Count < 1 Then
            MsgBox("You have to select a job to suspend!", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "No item selected")
            Exit Sub
        End If
        If ModBITS._SuspendJob(LViewJobs.SelectedIndices.Item(0)) <> True Then
            StatusSystemMessage.Text = "Error suspending job"
        Else
            StatusSystemMessage.Text = "Job suspended"
        End If
    End Sub

    Private Sub MnuJobsProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsProperties.Click
        Dim Frm As New FrmJob
        AddHandler Frm.EVENT_JOBDELETED, AddressOf _BuildLists
        Frm._Show(FrmJob.MODE_DISPLAY, LViewJobs.SelectedIndices.Item(0))
    End Sub

    Private Sub MnuFileProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFileProperties.Click
        Dim FileNumber As Integer
        Dim JobNumber As Integer
        Dim Information As String()
        If LViewDownloads.SelectedItems.Count < 1 Then
            MsgBox("You have to select a file", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "No File Selected")
            Exit Sub
        End If
        Information = Split(LViewDownloads.SelectedItems(0).Tag, "\")
        JobNumber = Information(0)
        FileNumber = Information(1)
        Dim Frm As New FrmFile
        Frm._Show(FrmJob.MODE_DISPLAY, JobNumber, FileNumber)

    End Sub


    Private Sub MnuToolsOptions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuToolsOptions.Click
        Dim Frm As New FrmOptions
        AddHandler FrmOptions.SETTINGSSAVED, AddressOf _SettingsSaved
        Frm.Show()
    End Sub

    ''' <summary>
    ''' Handler for the event, that the settings have been saved
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub _SettingsSaved()
        StatusMain.Text = "Your settings have been saved"
    End Sub

    Private Sub MnuHelpAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuHelpAbout.Click
        Dim Frm As New FrmAbout
        Frm.Show()
    End Sub

    Private Sub FrmMain_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If My.Settings.AlwaysShutDown Or sender.Equals(MnuFileExit) Or sender.Equals(CMnuNotifyIconExit) Then
            NotifyIcon.Visible = False
        Else
            e.Cancel = True
            NotifyIcon.BalloonTipIcon = ToolTipIcon.Info
            NotifyIcon.BalloonTipText = "Bandyt BITS is still running and your downloads remain active. You can make the application visible by clicking this message."
            NotifyIcon.BalloonTipTitle = "Bandyt BITS is still running"
            NotifyIcon.ShowBalloonTip(3000)
            Me.Hide()
        End If
    End Sub

    Private Sub CMnuNotifyIconExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuNotifyIconExit.Click
        NotifyIcon.Visible = False
        End
    End Sub

    Private Sub CMnuNotifyIconShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuNotifyIconShow.Click
        Me.Show()
    End Sub

    Private Sub NotifyIcon_BalloonTipClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon.BalloonTipClicked
        Me.Show()
    End Sub

    Private Sub NotifyIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon.MouseDoubleClick
        Me.Show()
    End Sub

    Private Sub MnuJobsFinish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuJobsFinish.Click
        If LViewJobs.SelectedItems.Count < 1 Then
            MsgBox("You have to select an item to complete!", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "No item selected")
            Exit Sub
        End If
        If ModBITS._JobFinished(LViewJobs.SelectedIndices.Item(0)) <> True Then
            MsgBox("You cannot finish a job, that is not transferred. Wait for the job to complete.", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Job not complete")
            Exit Sub
        End If
        If ModBITS._FinishJob(LViewJobs.SelectedIndices.Item(0)) = True Then
            StatusSystemMessage.Text = "Job completed sucessfully"
        Else
            StatusSystemMessage.Text = "Error completing job"
        End If
    End Sub

    Private Sub CMnuLViewJobProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuLViewJobProperties.Click
        MnuJobsProperties_Click(sender, e)
    End Sub

    Private Sub CMnuLViewJobsResume_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuLViewJobsResume.Click
        MnuJobsResume_Click(sender, e)
    End Sub

    Private Sub CMnuLViewJobsSuspend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuLViewJobsSuspend.Click
        MnuJobsSuspend_Click(sender, e)
    End Sub

    Private Sub CMnuLViewJobsFinish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuLViewJobsFinish.Click
        MnuJobsFinish_Click(sender, e)
    End Sub

    Private Sub CMnuLViewFilesProperties_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CMnuLViewFilesProperties.Click
        MnuFileProperties_Click(sender, e)
    End Sub

    Private Sub MnuViewUpdateNow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewUpdateNow.Click
        _BuildLists()
    End Sub

    Private Sub MnuViewUpdatespeedVeryHigh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewUpdatespeedVeryHigh.Click
        TimReload.Interval = 300
        TimReload.Start()
    End Sub

    Private Sub MnuViewUpdatespeedHigh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewUpdatespeedHigh.Click
        TimReload.Interval = 800
        TimReload.Start()
    End Sub

    Private Sub MnuViewUpdatespeedNormal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewUpdatespeedNormal.Click
        TimReload.Interval = 1500
        TimReload.Start()
    End Sub

    Private Sub MnuViewUpdatespeedSlow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewUpdatespeedSlow.Click
        TimReload.Interval = 3000
        TimReload.Start()
    End Sub

    Private Sub MnuViewUpdatespeedNever_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewUpdatespeedNever.Click
        TimReload.Stop()
    End Sub

    Private Sub MnuToolsStartService_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuToolsStartService.Click
        Try
            Controller.Start()
            StatusSystemMessage.Text = "Service started successfully"
        Catch ex As Exception
            StatusSystemMessage.Text = "Error starting service!"
        Finally
            StatusService.Text = "Status of Service: " & Controller.Status.ToString
        End Try
    End Sub

    Private Sub ToolStripResumeAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripResumeAll.Click
        MnuJobsResumeAll_Click(sender, e)
    End Sub

    Private Sub ToolStripSuspendAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripSuspendAll.Click
        MnuJobsSuspendAll_Click(sender, e)
    End Sub

    Private Sub FrmMain_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragDrop

    End Sub

    Private Sub MnuViewCurrentDownloads_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuViewCurrentDownloads.Click
        FrmCurrentDownloads.Visible = Not FrmCurrentDownloads.Visible
        FrmCurrentDownloads.Timer1.Enabled = FrmCurrentDownloads.Visible
    End Sub

    Private Sub MnuHelpContents_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuHelpContents.Click

    End Sub

    Private Sub MnuHelpReportBug_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuHelpReportBug.Click

    End Sub
End Class